package com.lin.blog.service.impl;

import com.lin.blog.constant.LikedStatusConstant;
import com.lin.blog.entity.UserLike;
import com.lin.blog.service.IUserLikedRedisService;
import com.lin.constant.RedisConstant;
import com.lin.utils.RedisUtils;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: blog
 * @description: 用户点赞服务 Redis操作
 * @author: Lin
 * @create: 2020-05-14 17:07
 **/
@Service
public class UserLikedRedisServiceImpl implements IUserLikedRedisService {

    /**
     * 点赞 状态为1
     * @param likedUserId
     * @param likedArticleId
     */
    @Override
    public void saveLiked2Redis(Long likedUserId, Long likedArticleId) {
        String key = generateLikedKey(likedUserId,likedArticleId);
        RedisUtils.hPut(RedisConstant.MAP_KEY_USER_LIKED,key, LikedStatusConstant.LIKE);
    }

    /**
     * 取消点赞 状态为0
     * @param likedUserId
     * @param likedArticleId
     */
    @Override
    public void unlikeFromRedis(Long likedUserId, Long likedArticleId) {
        String key = generateLikedKey(likedUserId,likedArticleId);
        RedisUtils.hPut(RedisConstant.MAP_KEY_USER_LIKED,key,LikedStatusConstant.UNLIKE);
    }



    /**
     * 从Redis中获取点赞数据
     * @return
     */
    @Override
    public List<UserLike> getLikedDataFromRedis() {
        Cursor<Map.Entry<Object, Object>> cursor = RedisUtils.opsForHash().scan(RedisConstant.MAP_KEY_USER_LIKED, ScanOptions.NONE);
        List<UserLike> list = new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object, Object> entry = cursor.next();
            String key = (String) entry.getKey();
            //分离出 likedUserId，likedPostId
            String[] split = key.split("::");
            Long likedUserId = Long.valueOf(split[0]);
            Long likedPostId = Long.valueOf(split[1]);
            Integer value = (Integer) entry.getValue();

            //组装成 UserLike 对象
            UserLike userLike = new UserLike(likedUserId, likedPostId, value);
            list.add(userLike);

            //存到 list 后从 Redis 中删除
            RedisUtils.opsForHash().delete(RedisConstant.MAP_KEY_USER_LIKED, key);
        }

        return list;
    }


    /**
     * 生成UserLike Key
     * @param likedUserId
     * @param likedArticleId
     * @return
     */
    public String generateLikedKey(Long likedUserId, Long likedArticleId){
        StringBuilder builder = new StringBuilder();
        builder.append(likedUserId);
        builder.append("::");
        builder.append(likedArticleId);
        return builder.toString();
    }
}
